import absanimateengine from "./absanimateengine";
import lgxcom from '../common/common'
import utilfuncs from "../common/tools/utilfuncs";
var funcs = utilfuncs.UtilFuncs;

import globalConst from "../common/globalConst";
var global = globalConst.GlobalConst;

class PistonEngine extends absanimateengine.AbsAnimateEngine {
    constructor(graph) {
        super(graph);
        this.type = "piston";
        this.stPoint = new lgxcom.LGXPoint();
        this.endPoint = new lgxcom.LGXPoint();
        this.destGraphBasePoint = new lgxcom.LGXPoint();
        this.curentScale = 1;
        this.dir = new lgxcom.LGXVector();
        this.plusFlag = true;//先膨胀，再收缩
        this.orginalGraphPos = graph.getPosCopy();
    }
    
    setCtrlPoint(st,end){
        this.stPoint.clone(st);
        this.endPoint.clone(end);
        this.dir.setBy2Pt(st,end);
    }

    setBasePoint(pt){
        this.destGraphBasePoint.clone(pt);
    }
    animate() {
        console.log("animate PistonEngine -------------------");
        
        let totalLenth = funcs.distancePoint(this.stPoint,this.endPoint,1);

        let baseProjPt = funcs.getPointProj2Line(this.destGraphBasePoint,this.stPoint,this.dir);
        let baseLenth = funcs.distancePoint(this.stPoint,baseProjPt,1);
        
        let curentPosList = this.destGraph.getPos().posList;
        let ptlist = this.orginalGraphPos.posList;
        let verticalVector = this.dir.rotateCopy(90);
        for (let i = 0;i < ptlist.length;i++){
            let curentPt = ptlist[i];
            let projPt = funcs.getPointProj2Line(curentPt,this.stPoint,this.dir);
            let dis = funcs.distancePoint(projPt,this.stPoint);
            if (dis < global.ZERO_8E){
                continue;
            }

            if (funcs.chkPointOnLineSec(projPt, this.stPoint, this.endPoint))
            {
                let lenth = funcs.distancePoint(this.stPoint,projPt,1);
                let curentLen = (this.curentScale*totalLenth*lenth)/baseLenth;
                let x = this.stPoint.x + curentLen*this.dir.m;
                let y = this.stPoint.y + curentLen*this.dir.n;
                let newProjPt = {x,y};
                let interPoint = funcs.getTwoLineInterPos(newProjPt,verticalVector,curentPt,this.dir);
                let destPoint = curentPosList[i];
                destPoint.x = interPoint.x;
                destPoint.y = interPoint.y;
            }
        }
        this.destGraph.calScope(1);

        if (this.plusFlag){
            this.curentScale += this.speed;
            if (this.curentScale > 1){
                this.plusFlag = false;
            }
        }
        else{
            this.curentScale -= this.speed;
            if (this.curentScale < 0.0001){
                this.plusFlag = true;
            }
        }
    }
}

export default { PistonEngine }